package org.tacticalTroopers.jme.server;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

public class Scheduler {

	final static Log log = LogFactory.getLog(Scheduler.class);

	Long lastTop;
	Long startTime;
	//Integer noFramePerSecond;
	Integer frameDuration;

	public void startAtNextSecond(){
		long timeToWait = 1000 - getCurrentMilliseconds();
		try {
			Thread.sleep(timeToWait);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void setNoFramePerSecond(Integer noFramePerSecond){
		//this.noFramePerSecond = noFramePerSecond;
		this.frameDuration = 1000 / noFramePerSecond;
		//System.out.println(frameDuration+" ms");
	}
	
	public void setFrameDuration(Integer noMillisecond){
		//this.noFramePerSecond = noFramePerSecond;		
		this.frameDuration = noMillisecond;
		//System.out.println(frameDuration+" ms");
	}

	Long tmpNow;
	public void waitToNextTop(){
		tmpNow = System.currentTimeMillis();
		if(lastTop==null){
			lastTop = tmpNow;
		}
		Long spentTime = tmpNow - lastTop;
		Long timeToWait = frameDuration-spentTime;
		if(timeToWait>0){
			try {
				Thread.sleep(timeToWait);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}	    
		}else{
			log.error("not real time !");
		}
		lastTop = System.currentTimeMillis();
	}

	public Long getCurrentMilliseconds(){
		return System.currentTimeMillis() % 1000;
	}

	public static void main(String[] args) {
		PropertyConfigurator.configure("log4j.properties");
		Scheduler s = new Scheduler();

		s.setNoFramePerSecond(1);

		s.startAtNextSecond();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:S");
		int i=0;
		while(i<50){
			log.debug("top "+sdf.format(Calendar.getInstance().getTime()));
			//log.debug(s.getCurrentMilliseconds());
			s.waitToNextTop();
		}

	}
}
